package main

import (
	"log"
	"math/rand"
	"net/http"
	"net/http/httputil"
	"net/url"
)

type handle struct {
	addrs []string
}

func (h *handle) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	addr := h.addrs[rand.Int()%len(h.addrs)]
	remote, err := url.Parse("http://" + addr)
	if err != nil {
		panic(err)
	}
	proxy := httputil.NewSingleHostReverseProxy(remote)
	proxy.ServeHTTP(w, r)
}

// go run server.go --port 3001
// go run server.go --port 3000

func main() {
	//被代理的服务器host和port
	h := &handle{}
	h.addrs = []string{"localhost:3001", "localhost:3002"}

	err := http.ListenAndServe(":9090", h)
	if err != nil {
		log.Fatalln("ListenAndServe: ", err)
	}
}
